import java.util.Objects;

public class Solution {

    /**
     * 给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。
     * 你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。
     */
    public ListNode swapPairs(ListNode head) {
        if (Objects.isNull(head)) {
            return null;
        }
        if (Objects.isNull(head.next)) {
            return head;
        }

        ListNode point = head;
        ListNode next = point.next;
        if (Objects.isNull(next.next)) {
            head = next;
            next.next = point;
            point.next = null;
            return head;
        } else {
            point.next = next.next;
            next.next = point;
            head = next;
        }

        ListNode pre = point;
        point = point.next;
        next = point.next;
        while (Objects.nonNull(next)) {
            point.next = next.next;
            next.next = point;
            pre.next = next;

            if (Objects.isNull(point.next)){
                break;
            }
            pre = point;
            point = point.next;
            next = point.next;
        }

        return head;
    }

}
